package com.navinfo.opentsp.platform.computing.parallel.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

/**
 * @author  yangmg on 2016/3/7.
 */
public class PropertiesUtil {
    private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
    private static String FILE_NAME = "config.properties";
    private static Map<String,String> allParam = new HashMap<>();

    public static Properties loadProperty (){
        Properties properties = new Properties();
        try(
            InputStream inputStream = PropertiesUtil.class.getClassLoader().getResourceAsStream(FILE_NAME);
        ) {
            properties.load(inputStream);
        } catch (IOException e) {
            logger.error("init "+FILE_NAME+" error",e);
        }

        logger.info("成功初始化配置文件【"+FILE_NAME+"】");
        return properties;
    }

    public static String getPropertiesByKey(String fileName, String key){
        if(allParam.containsKey(key)){
            return allParam.get(key);
        }

        allParam.clear();
        Properties p = new Properties();
        try(
                InputStream inputStream = PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName);
        ) {
            p.load(inputStream);
        } catch (IOException e) {
            logger.error("init "+FILE_NAME+" error",e);
        }

        Set<Entry<Object, Object>> allKey = p.entrySet();
        for (Entry<Object, Object> entry : allKey) {
            allParam.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
        }
        logger.info("成功初始化配置文件【"+fileName+"】");
        return allParam.get(key);
    }


    public static Map<String,String> getProperties(){
        try(
                InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream(FILE_NAME);
        ) {
            if(allParam.size()==0){
                Properties p = new Properties();
                p.load(in);
                Set<Entry<Object, Object>> allKey = p.entrySet();
                for (Entry<Object, Object> entry : allKey) {
                    allParam.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
                }
                in.close();
                return allParam;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return allParam;
    }

    public static String getProperties(String key){
        return getPropertiesByKey(FILE_NAME, key);
    }
}
